package com.easipass.framework.eirframeworkcoredsl;

import java.util.HashMap;
import java.util.Map;

public class AppValidationProblem {

    private final String appDsl;

    private final int offset;

    private final DSLMessage message;

    public AppValidationProblem(String appDsl, int offset, DSLMessage message) {
        this.appDsl = appDsl;
        this.offset = offset;
        this.message = message;
    }

    public String toString() {
        return message.formatMessage(offset);
    }

    public String toStringWithContext() {
        StringBuilder s = new StringBuilder();
        s.append(message.formatMessage(offset));
        int startOfLine = getStartOfLine(offset);
        if (appDsl != null && appDsl.length() > 0) {
            s.append("\n").append(appDsl.substring(startOfLine)).append("\n");
        }
        int offsetOnLine = offset - startOfLine;
        if (offsetOnLine >= 0) {
            for (int i = 0; i < offsetOnLine; i++) {
                s.append(' ');
            }
            s.append("^\n");
        }
        return s.toString();
    }

    public DSLMessage getMessage() {
        return message;
    }

    public int getOffset() {
        return offset;
    }

    private int getStartOfLine(int position) {
        for (int p = 0; p < position; p++) {
            if (appDsl.charAt(p) == '\n') {
                return p + 1;
            }
        }
        return 0;
    }

    public Map<String, Object> toExceptionDescriptor() {
        Map<String, Object> descriptor = new HashMap<>();
        String text = message.formatMessage(offset);
        descriptor.put("message", text);
        descriptor.put("position", offset);
        return descriptor;
    }
}
